package com.ridanlabs.professorwebsite.controller;

import java.util.logging.Logger;

import javax.validation.Valid;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.ridanlabs.professorwebsite.Util;
import com.ridanlabs.professorwebsite.general.CourseForm;
import com.ridanlabs.professorwebsite.general.CourseSeason;
import com.ridanlabs.professorwebsite.models.Course;
import com.ridanlabs.professorwebsite.models.DAO;
import com.ridanlabs.professorwebsite.models.UserProfile;

@Controller
public class CourseController {
	private static final Logger log = Logger.getLogger(CourseController.class.getName());
	
	@PreAuthorize("hasRole('PROFESSOR')")
	@RequestMapping(value="/course/add", method=RequestMethod.GET)
	public CourseForm add() {
		CourseForm courseForm = new CourseForm();
		
		return courseForm;
	}
	
	@PreAuthorize("hasRole('PROFESSOR')")
	@RequestMapping(value="/course/add", method=RequestMethod.POST)
	public String add( @Valid CourseForm form, BindingResult result ) {
		if( result.hasErrors() ) return null; //if Binding to modal had errors, show errors
		
    	DAO dao = new DAO();
    	UserProfile user = Util.getAuthenticatedUser();
    	Course course = new Course();
    	
    	String courseId = (form.getSeason() + "_" + form.getCourseName() + "_" + form.getSection()).toLowerCase();
    	
    	course.setId( courseId );
    	course.setCourseName( form.getCourseName() );
    	course.setSeason( CourseSeason.fromString(form.getSeason()) );
    	course.setSection( form.getSection() );
    	course.setCourseProfessor( user.getKey() );
    	
    	user.addCourse( course.getKey() );
    	
    	if( dao.findCourse(course.getId()) == null ) {
    		dao.saveCourse( course );
    		dao.saveUserProfile( user );
    	} else {
    		log.warning( user.getUserEmail() + " tried to add a course which already exists.");
    	}
    	
    	return "redirect:/professor/index";
	}

}
